const mongoose = require('mongoose');
const User = require('../models/user.models');

exports.create = function (req,res,next) {
    const user = new User(req.body);
    user.save().then(data=>{
        res.json(data);
    });
};

exports.get = function (req,res,next) {
  const id = req.params.id;
  User.findById(id,function(err,result){
    res.json(result);
  })
};

exports.update = function (req,res,next) {
  const id = req.params.id;
  User.findByIdAndUpdate(id,{ $set:req.body },{ new:false }).then(data=>{
    res.json(data);//data:更新之前的数据
  })
};

exports.delete = function (req,res,next) {
  const id = req.params.id;
  User.findByIdAndRemove(id,function(err,doc){
    res.json({message:'数据删除成功',status:200});
  })
};

exports.removes = function (req, res, next) {
  const ids = req.body.ids.split(',');//将id拆分成数组
  if (ids.length > 0) {
    User.remove({ _id: { $in: ids } }).then(data => {
      res.json({ status: 200, message: '删除多条数据成功' });
    });
  }
}

exports.list = function (req,res,next) {
  var page = req.body.page ? req.body.page : 1;
  var rows = req.body.rows ? req.body.rows : 5;
  var quertCondition = {};
 
  if(req.body.email && req.body.email.trim().length > 0){
    quertCondition={
      email : new RegExp(req.body.email,'i')
    }
  }
  // if(Object.getOwnPropertyNames(req.body).length > 2) {
  //   for (const key in req.body) {
  //       if(key != 'limit' && key != 'page') {
  //           quertCondition[key]  = new RegExp(req.body[key], 'i');
  //       }
  //   }
  // }
  User.paginate(quertCondition, { page: +page, limit: +rows }, function(err, result) {
    result.rows = result.docs;
    delete result.docs;
    res.json(result);
  });
};
